<?php
/**
 * Created by PhpStorm.
 * User: jsq
 * Date: 2017/12/1 0001
 * Time: 16:46
 */

namespace app\admin\logic;

use app\admin\model\AuthGroup;
use app\admin\model\Users as Users_model;
use app\admin\model\AuthGroupAccess;
use think\Cache;

class User
{
    private $users_model = '';

    public function __construct(){
        $this->users_model = new Users_model();
    }

    /**
     * 获取所有的状态（供获取器使用）
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public static function usersToText(){
        $states = self::getAllUsers();
        $states = collect($states)->column('usersname','id');
        return $states;
    }

    /**
     * 获得所有的用户（从缓存中）
     * @return false|mixed|\PDOStatement|string|\think\Collection   返回数组
     */
    public static function getAllUsers(){
        if (!empty(Cache::get('allUsers'))){
            return Cache::get('allUsers');
        }else{
            $users = Users_model::all();
            foreach ($users as $v){
                $auth = db('auth_group_access')->where(['uid'=>$v['id']])->find();
                $authgroup['auth_id'] = $auth['group_id'];
                $users = array_merge($v->toArray(),$authgroup);
                $user[] = $users;
            }
            Cache::set('allUsers',$user);
            return $user;
        }
    }

    /**
     * 根据id来获取用户信息
     * @param $uid
     * @param bool $force
     * @return mixed
     * @author: Huang
     */
    public function getOneUserById($uid, $force = false)
    {
        $userinfo = Cache::tag('alluser')->get('userinfo' . $uid);
        if (empty($userinfo) || $force) {
            $userinfo = collect($this->getAllUsers())->where('id', $uid)->first();
            Cache::tag('alluser')->set('userinfo' . $uid, $userinfo);
        }
        return $userinfo;
    }

    /**
     * 获取启用的状态
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getEnabledUsers(){
        $states = $this->getAllUsers();
        $states = collect($states)->where('status',1)->all();
        $states = collection($states)->toArray();
        $states = array_merge($states);
        return $states;
    }

    public function addUser($data){
        if(empty($data)){
            return ['result'=>2,'msg'=>'数据丢失'];
        }

        if(!empty($data['password'])){
            if( $data['password'] != $data['repassword']){
                return ['result'=>2,'msg'=>'密码和重复密码不一致'];
            }else{
                $data['password'] = md5( $data['password']);
                unset($data['repassword']);
            }
        }else{
            $data['password'] = md5('121314');
            unset($data['repassword']);
        }


        $data['status'] = 1;//自动启用
        $result = $this->users_model->allowField(true)->validate(true)->save($data);
        if($result == false){
            return ['result'=>2,'msg'=>$this->users_model->getError()];
        }else{
            $authgroup = new AuthGroup();
            $authgroup->addToGroup($this->users_model->id,$data['role_id']);
            Cache::rm('allUsers');
            return ['result'=>1,'msg'=>'新增成功'];
        }
    }

    public function editUser($data){
        if(empty($data)){
            return ['result'=>2,'msg'=>'数据丢失'];
        }
        if(empty($data['id'])){
            return ['result'=>2,'msg'=>'ID丢失'];
        }

        if(!empty($data['password'])){
            if( $data['password'] != $data['repassword']){
                return ['result'=>2,'msg'=>'密码和重复密码不一致'];
            }else{
                $data['password'] = md5( $data['password']);
                unset($data['repassword']);
            }
        }else{
            unset($data['password']);
            unset($data['repassword']);
        }

        $result = $this->users_model->allowField(true)->validate('Users.edit')->isUpdate(true)->save($data);
        if($result == false){
            return ['result'=>2,'msg'=>$this->users_model->getError()?:'没有需要修改的数据'];
        }else{
            $_REQUEST['batch'] =true;//清除以前的角色
            $authgroup = new AuthGroup();
            $authgroup->addToGroup($data['id'],$data['role_id']);

            Cache::rm('allUsers');
            return ['result'=>1,'msg'=>'修改成功'];
        }
    }
    public function delUser($id){
        if ( empty($id) ) {
            return ['result'=>false,'msg'=>'请选择要操作的数据'];
        }
        if(Users_model::get($id)){
            if(Users_model::destroy($id)){
                Cache::rm('allUsers');
                return ['result'=>true,'msg'=>'删除成功'];
            } else {
                return ['result'=>false,'msg'=>'删除失败'];
            }
        }else{
            return ['result'=>false,'msg'=>'要删除的数据不存在'];
        }
    }




}